//成果转化
<template>
  <div class="flex-1 flex-ver">
    <div class="mb8">
      <search @clearSearch='clearSearch' :status='true'>
        <el-form label-width='80px' inline autocomplete="off"  :model="pageparm" class="search_box">
          <el-form-item label="专利名称">
            <inputSearch ref="search_p" type="patent" @onChange='searchChane($event,"patents_id")'/>
          </el-form-item>
          <el-form-item label="合同名称">
            <el-input size="medium"  v-model.trim="pageparm.name" placeholder="请输入合同名称搜索" clearable />
          </el-form-item>
          <el-form-item label="合同编号">
            <el-input size="medium"  v-model.trim="pageparm.contract_code" placeholder="请输入合同编号搜索" clearable />
          </el-form-item>
          <el-form-item label="审核状态">
            <el-select size="medium" clearable v-model="pageparm.review_status" placeholder="请选择审核状态搜索" @change='searchChane($event,"review_status")'>
              <el-option
                v-for="item in reviewStatus"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button v-permission="{action:'成果转化添加',effect:'delete'}" class="mr8" size="medium" type="primary" @click="handle(null,{},3)">新增成果转化</el-button>
          <exportExcel :apiFn='Apipatentcontracts' name='成果转化' :self='true' :dataFn='dataFn' />
        </template>
      </search>
    </div>
    <el-table
      :data="tableData"
      class="flex-1"
      height="100%" size="medium" 
      border 
      highlight-current-row
      v-loading="tableLoading"
      stripe
      @sort-change="tableSortChange">  
      <el-table-column
        align="center"
        v-for="(item,i) in headerList"
        :key="item.prop"
        :prop="item.prop"
        :label="item.label"
        :width="item.width"
        :fixed="i === 0 ? true: false"
        show-overflow-tooltip
        sortable="custom">
        <template slot-scope="scope">
          <template v-if="item.prop === 'patents_id'">
            {{ scope.row.patent?scope.row.patent.name:'' }}
          </template>
          <template v-else-if="item.prop === 'review_status'">
            <span v-if="scope.row.review_status === 2" class="c-red">{{reviewStatusObj[scope.row.review_status]}}：{{scope.row.review_comment}}</span>
            <span v-else>{{reviewStatusObj[scope.row.review_status]}}</span>
          </template>
          <template v-else>
           {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>
      <el-table-column  align="center" label="附件" width="180">
        <template slot-scope="scope">
          <div v-if="scope.row.attachment.length > 0">
            <el-image
              :z-index='3000'
              v-for="item in echoFiles(scope.row.attachment,true)" :key='item.id'
              class="table_cell--image"
              :src="uploadUrl + item.path" 
              :preview-src-list="srcList(echoFiles(scope.row.attachment,true))">
            </el-image>
            <p v-for="v in echoFiles(scope.row.attachment,false)" :key="v.path">
              <el-tooltip  effect="dark" :content="v.file_name" placement="top-end">
                <span class="shou xialine overhide_" @click="uploadFiles(v.path,v.file_name)">{{v.file_name}}</span>
              </el-tooltip>
            </p>
          </div>
        </template>
      </el-table-column>
      <el-table-column fixed="right" align="center" label="操作" width="135">
        <div class="flex-justify-end" slot-scope="scope">
          <el-tooltip  effect="dark" :content="scope.row.review_status == 1 ? '退审':'审核'" placement="bottom-end" v-show="scope.row.review_status != 2">
            <el-button v-permission="{action:'成果转化审核',effect:'delete'}" 
                      :type="scope.row.review_status == 1?'warning':'primary'"
                      @click="examine_btns(scope.row,1)" size="small"  
                      :icon="scope.row.review_status == 1 ? 'el-icon-close' : 'el-icon-help'" circle></el-button>
          </el-tooltip>
          <el-tooltip  effect="dark" content="修改信息" placement="bottom-end">
            <el-button v-permission="{action:'成果转化编辑',effect:'delete'}" size="small"  @click="handle(scope.$index, scope.row,2)" icon="el-icon-edit" circle></el-button>
          </el-tooltip>
          <!-- v-permission="{action:'成果转化删除',effect:'delete'}" -->
          <el-tooltip effect="dark" content="删除" placement="bottom-end">
            <el-button v-if="scope.row.delete" size="small" type="danger" @click="deleteUser(scope.$index, scope.row)" icon="el-icon-delete" circle></el-button>
          </el-tooltip>
        </div>
      </el-table-column>
    </el-table>

    <Pagination v-bind:child-msg="pageparm" @callFather="callFather"></Pagination>

    <el-dialog :visible.sync="editFormVisible" width="740px" @close='dialogClose' @closed="btnLoading = false" top="10vh"
    :close-on-click-modal='false'
    :close-on-press-escape='false'>
      <h2 slot="title" class="tx-c">{{dialogTitle}}</h2>
      <el-form autocomplete="off"  label-width="120px" :model="editForm" class="form_flex">
        <el-form-item
          v-for="(v, i) in editHeaderList"
          :key="i"
          :label="v.label"
          :class="v.required ? 'tip' : ''">
          <inputSearch v-if="v.prop === 'patents_id'" ref="p_id" type="patent" @onChange='patentChange' :middleList="middleList" />
          <el-date-picker
            v-else-if="v.prop === 'start_time' || v.prop === 'end_time'"
            size="medium"
            v-model="editForm[v.prop]"
            type="date"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :placeholder="'请选择'+ v.label"
            :picker-options='pickerOptions[v.prop]'
            @change="changeDate($event,v.prop)">
          </el-date-picker>
          <el-input
            v-else
            size="medium"
            :type="v.type"
            autosize
            clearable
            v-model="editForm[v.prop]"
            @mousewheel.native.prevent
            :placeholder="'请输入' + v.label"/>
        </el-form-item>
        <el-form-item label="附件上传">
          <el-upload
            style="width: 500px"
            multiple
            action="/"
            :on-change='onChangeFile'
            :on-remove="onRemoveFile"
            :auto-upload="false"
            :file-list=fileList>
            <el-button size="medium" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="已上传附件" v-if="editForm.attachment && editForm.attachment.length > 0">
          <div style="width: 500px">
            <p v-for="v in editForm.attachment" :key="v.path" class="flex-space-between">
              <span class="shou xialine overhide_ mr16" @click="uploadFiles(v.path,v.file_name)">{{v.file_name}}</span>
              <i class="el-icon-close f-14" @click="delFiles(v)"></i>
            </p>
          </div>
        </el-form-item>
      </el-form> 
      <div slot="footer" class="flex-justify-bcenter">
        <el-button @click="editFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit" :loading='btnLoading'>确 定</el-button>
      </div>
    </el-dialog>
    
    <!-- 审核 -->
    <examine ref="examine" @submit='examineSubmit' :comeBack='comeBack' />   

  </div>
</template>

<script>

import {
  Apipatentcontracts,
  ApipatentcontractsAdd,
  ApipatentcontractsPut,
  ApipatentcontractsDel,
  ApipatentcontractsCheck,
  ApiupLoadFiles
} from '@/api'
import {reviewStatus,reviewStatusObj} from "@/assets/js"
import {debounce,utils_upload } from "@/utils/index";
import {headerList} from '../js/conversion'
import {isIMage} from "@/utils/test";
import {uploadUrl} from '@/api/request'
export default {
  computed:{
      editHeaderList(){
        let list = headerList.filter(item=> item.prop !== 'review_status')
        return list.sort((a,b) => b.required - a.required)
      }
  },
  data(){
    return{
      Apipatentcontracts,
      uploadUrl:uploadUrl(),
      reviewStatus,
      reviewStatusObj,
      tableData:[], 
      editFormVisible: false, 
      editForm: {
        id:'',
        patents_id:'',
        name:'',
        contract_code:'',
        first_party_name:'',
        first_party_person:'',
        second_party_name:'',
        second_party_person:'',
        start_time:'',
        end_time:'',
        attachment:[],
      },  //修改或者查看详情

      pageparm: {
        page: 1,
        perPage: 20,
        total: null,
        sort_str: null, 
        sort_order: 'desc' ,
      },
      tableLoading: false,

      btnLoading: false,

      headerList,
      rules:['name','patents_id','contract_code','first_party_name','first_party_person','second_party_name','second_party_person'],

      examine_id: null,  //审核id
      comeBack: false,

      middleList:[],
      dialogTitle: '',

      fileList: [],
      pickerOptions:{
        start_time:{},
        planned_completion_time:{},
      }
    }
  },
  mounted(){
    this.getList()
  },
  methods:{
    echoFiles(arr=[],flag=true){
      return arr.filter(item => isIMage(item.file_name) === flag)
    },
    srcList(arr=[]){
      return arr.map(item => this.uploadUrl + item.path)
    },
    changeDate(t){
      this.pickerOptions = {
        start_time:{
           disabledDate: (time) => {
            if (this.editForm.end_time) {
              return (time.getTime() >= new Date(this.editForm.end_time).getTime());
            }
            // else{
            //   return time.getTime() < (Date.now() - 86400000)
            // }
          }
        },
        end_time:{
          disabledDate: (time) => {
            if (this.editForm.start_time) {  // 开始日期
              return (time.getTime() < new Date(this.editForm.start_time).getTime() - 86400000);
            }
            // else{
            //   return time.getTime() < Date.now() - 86400000
            // }
          }
        },
      }
    },
    dataFn(data,tableHeade){
      let tabStr = ''
      data.forEach((item, index) => {
          let tabRowStr = "";
          tabStr += `<tr>`;
          for (let i = 0; i < tableHeade.length; i++ ) {
            const key = tableHeade[i]
            if (key === 'patents_id'){
              tabRowStr += `<td>${item.patent?item.patent.name:''}</td>`;
            }else if(key === 'review_status'){
              tabRowStr += `<td>${reviewStatusObj[item.review_status]}${item.review_comment?('：' + item.review_comment):''}</td>`;
            }else {
              tabRowStr += `<td>${item[key] || ''}</td>`;
            }
          }
          tabStr += tabRowStr;
          tabStr += "</tr>";
      });
      return tabStr
    },
    uploadFiles: debounce(function (url,name){
      utils_upload(url,name)
    },500,true),
    delFiles(v){
      this.editForm.attachment = this.editForm.attachment.filter(item => item.id !== v.id)
    },
    onChangeFile(file, fileList){
      this.fileList.push(file)
    },
    onRemoveFile(file, fileList){
      this.fileList = fileList
    },
    //审核
    examineSubmit(options){
      const loading = this.$loading({
        lock: true,
        text: '加载中...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      options.id = this.examine_id
      ApipatentcontractsCheck(options,options.id).then(res => {
        this.getList()
      }).catch(()=>{
        this.$message.error('服务器错误，请重新提交');   
      }).finally(()=>{
        loading.close()
      })
    },
    examine_btns(item,i){
      this.examine_id = item.id
      if(item.review_status == 1){
        this.comeBack = true
        this.$refs.examine.options.review_status = 2
      }else{
        this.comeBack = false
        this.$refs.examine.options.review_status = null
      }
      this.$refs.examine.examineShow = true

    },
    echo(i,arr){
      let label
      for (const item of arr) {
        if(item.value === i){
          label = item.label
          break;
        }
      }
      return label
    },
    tableSortChange(column){
      if (column.order === "descending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "desc";
      } else if (column.order === "ascending") {
        this.pageparm.sort_str = column.prop;
        this.pageparm.sort_order = "asc";
      }else{
        this.pageparm.sort_str = null;
        this.pageparm.sort_order = null;
      }
      this.getList()
    },
    //搜索
    clearSearch(){
      this.$refs.search_p.clear()
    },
    searchChane(i,val){
      this.pageparm[val] = i
      this.pageparm.page = 1
      this.getList()
    },
    //分页
    callFather(pageparm){
      this.pageparm.page = pageparm.page
      this.pageparm.perPage = pageparm.perPage
      this.getList()
    },
    getList(){
      this.tableLoading = true
      Apipatentcontracts(this.pageparm).then(({data,page}) => {
        this.tableData = data || []
        this.pageparm.total = page.total
        this.tableLoading = false
      }).catch(()=>{
        this.tableLoading = false
      })
    },
    handle(index,value,i){
      for (const key in this.editForm) {
        this.editForm[key] = value[key]
      }
      this.editFormVisible = true
      this.changeDate()
      this.dialogTitle = '新增成果转化'
      if(i == 2){
        this.editForm.attachment = [...value.attachment]
        this.dialogTitle = '编辑成果转化'
        this.$nextTick(()=>{
          this.middleList = [{id:value.patent.id ,name: value.patent.name}]
        })
      }
    },
    e_id({id,name}){
        this.editForm.first_inventor_id = id
        this.editForm.first_inventor = name
    },
    patentChange(id){
      this.editForm.patents_id = id
    },
    chengGuoChange(id){
      this.editForm.finding_id = id
    },
    dialogClose(){
      this.$refs.p_id[0].clear()
      this.fileList = []
    },
    deleteUser(index,value){
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true,
            text: '加载中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          ApipatentcontractsDel(value.id).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.getList()
          }).finally(()=>{
            loading.close()
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    submit : debounce(function(){   //提交  修改或新增
      const options = this.editForm
      for (const key of this.rules) {
        if(!options[key] && options[key] !== 0){
          this.$message({
            type: 'error',
            message: '必填信息请填写完整！'
          });
          return
        }
      }
      this.btnLoading = true
      const formData = new FormData()
      for (const i in options) {
        if(i !== 'attachment') {
          if(options[i] === null || options[i] === undefined)options[i] = ""
          formData.append(i,options[i])
        }
      }
      if(this.fileList.length > 0){
        this.fileList.forEach(item=>{
          formData.append('files[]',item.raw)
        })
      }
      if(options.id){   //有ID就是修改
      if(options.attachment && options.attachment.length > 0){
            options.attachment.forEach(item =>{
              formData.append('file_name[]',item.file_name)
              formData.append('file_path[]',item.file_path)
            })
        }else{
          formData.append('file_name[]',[])
          formData.append('file_path[]',[])
        }
        ApipatentcontractsPut(formData,options.id,{
          headers:{'Content-Type':'multipart/form-data'}
       }).then(res => {
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.editFormVisible = false
          this.getList()
        }).catch(()=>{
          this.btnLoading = false
          this.$message({
            type: 'error',
            message: '修改失败!'
          });
        })
      }else{
        ApipatentcontractsAdd(formData,{
        headers:{'Content-Type':'multipart/form-data'}
      }).then(res => {
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          this.editFormVisible = false
          this.getList()
        }).catch(()=>{
          this.btnLoading = false
          this.$message({
            type: 'error',
            message: '添加失败!'
          });
        })
      }
    },800,true)
  },

}
</script>
<style lang='less' scoped>
</style>